singleApp.controller('testimgcropCtrl', ['$http', '$scope', 'AppDataService', 'FileUpload', 'Session', function ($http, $scope, AppDataService, FileUpload, Session) {
    $scope.model_common = { thumb: "" };
    /*
     * Upload thumb file
     */
    $scope.model_cropthumbimg = { myImage: "", myCroppedImage: "", img_type: "", filename: "", bounds: { left: 0, right: 0, top: 0, bottom: 0 }, progress: 0 };
    $scope.onFileSelectPhoto = function ($files) {
        if ($files == null || $files.length == 0)
            return;

        var file = $files[0];
        var reader = new FileReader();
        reader.onload = function (evt) {
            $scope.$apply(function ($scope) {
                $scope.model_cropthumbimg = { myImage: evt.target.result, myCroppedImage: "", img_type: file.type, filename: file.name, bounds: { left: 0, right: 0, top: 0, bottom: 0 }, progress: 0 };
            });
            layer.open({
                type: 1,
                title: 'Crop Img',
                content: $('#divCropThumbImg'),
                area: ['800px', '650px'],
                cancel: function (index) {
                    layer.closeAll();
                }
            });
        };
        reader.readAsDataURL(file);
    };

    $scope.converBase64ToFile = function (dataURI) {
        // convert base64/URLEncoded data component to raw binary data held in a string
        var byteString;
        if (dataURI.split(',')[0].indexOf('base64') >= 0)
            byteString = atob(dataURI.split(',')[1]);
        else
            byteString = unescape(dataURI.split(',')[1]);

        // separate out the mime component
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

        // write the bytes of the string to a typed array
        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }

        return new Blob([ia], { type: mimeString });
    };

    $scope.confirmCropThumbImg = function () {
        layer.load(2);
        var api_url = window.singleConfig.rootUrl + "api/common/FileService/uploadWorkImg";
        $http({
            method: 'POST',
            url: api_url,
            eventHandlers: {
                readystatechange: function (event) {
                    if (event.currentTarget.readyState === 4) {
                        console.log("readyState=4: Server has finished extra work!");
                    }
                }
            },
            uploadEventHandlers: {
                progress: function (e) {
                    if (e.lengthComputable) {
                        progress = Math.round(e.loaded * 100 / e.total);
                        console.log("progress: " + progress + "%");
                        $scope.model_cropthumbimg.progress = progress;
                        if (e.loaded == e.total) {
                            console.log("File upload finished!");
                            console.log("Server will perform extra work now...");
                        }
                    }
                }
            },
            data: $.param({
                img_content: $scope.model_cropthumbimg.myCroppedImage,
                img_type: $scope.model_cropthumbimg.img_type
            }),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
        .then(function (data) {
            if (data.data.code == "success") {
                $scope.model_common.thumb = data.data.FileName;
                layer.closeAll();
            }
        }, function (data) {
            layer.closeAll();
            layer.msg("Error to save croped image.");
        });
        //layer.load(2);
        //var uploadPhotoProperties = function (data) {
        //    if (data.data.code == "success") {
        //        if ($scope.model_cropthumbimg.step == null)
        //            $scope.model_common.thumb = data.data.FileName;
        //        else
        //            $scope.model_cropthumbimg.step.meta_value = data.data.FileName;
        //        layer.closeAll();
        //    }

        //};

        //var action = $scope.model_cropthumbimg.step != null ? "uploadStepCropFile" : "uploadRawCropFile2";
        //var blob = $scope.converBase64ToFile($scope.model_cropthumbimg.myCroppedImage);
        //var file = new File([blob], $scope.model_cropthumbimg.filename, { type: $scope.model_cropthumbimg.img_type });

        //if (file != null && file != undefined) {
        //    FileUpload.upload(file, action).then(uploadPhotoProperties);
        //}
    };
}]);